package com.example.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.ResultMsgVo;
import com.example.demo.entity.MapVo;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("test")
public class TestController {
    @Autowired
    private IUserService userService;
    @Autowired
    private UserMapper userMapper;


    @RequestMapping(value = "findAllUserList",method = RequestMethod.POST)
    public ResultMsgVo<List<User>> findAllUserList() {

        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);

        return new ResultMsgVo<>(users);
    }

    @RequestMapping(value = "insertUser",method = RequestMethod.POST)
    public ResultMsgVo<Integer> insertUser(@RequestBody User user){
        // 默认雪花算法自动生成ID type = ID_WORKER

        return new ResultMsgVo<>(userMapper.insert(user));
    }

    @RequestMapping(value = "deleteUserById",method = RequestMethod.POST)
    public ResultMsgVo<Integer> deleteUserById(@RequestBody User user){

        return new ResultMsgVo<>(userMapper.deleteById(user.getId()));
    }

    @RequestMapping(value = "updateUser",method = RequestMethod.POST)
    public ResultMsgVo<Integer> updateUser(@RequestBody User user){
//        user.setId(8L);
//        user.setName("王五");
//        user.setAge(3);
//        user.setEmail("11922@qq.com");
        // 默认雪花算法自动生成ID type = ID_WORKER
        return new ResultMsgVo<>(userMapper.updateById(user));
    }

    // 条件查询 -- map
    @RequestMapping(value = "getUser",method = RequestMethod.POST)
    public ResultMsgVo<List<User>> getUser(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("age",3);
        System.out.println("666");
        List<User> users = userMapper.selectByMap(map);
        return new ResultMsgVo<>(users);
    }

    // 分页查询
    @RequestMapping(value = "getUserPage",method = RequestMethod.POST)
    public ResultMsgVo<Page<User>> getUserPage(@RequestBody MapVo mapVo){
        Page<User> page = new Page<>(mapVo.getPage(), mapVo.getSize());
        userMapper.selectPage(page, null);

//        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        wrapper.ge("age",12);
//        userMapper.selectList(wrapper);
        return new ResultMsgVo<>(page);
    }

    // 乐观锁测试
    @RequestMapping(value = "lockTest",method = RequestMethod.POST)
    public ResultMsgVo<Integer> lockTest(){
        User user = userMapper.selectById(8L);
        user.setEmail("1@qq.com");
        return new ResultMsgVo<>(userMapper.updateById(user));
    }

}
